//
//  GBLoveMatchHeaderView.swift
//  APSwift
//
//  Created by jianbo.pei on 2022/8/19.
//

import UIKit
import APExtensions
import SnapKit
import SVGAPlayer

class GBLoveMatchHeaderView: APBaseView {
    private var radarImageView: UIImageView!
    private var heartImageView: UIImageView!
    private var loopView: GBChatMatchHeadLoopView!
    lazy var speedUpMatchingLabel: UILabel = {
        let lb = UILabel.ap.lb(.ap.regular(14), .ap.hex("FD719C")).then { make in
            addSubview(make)
            make.isHidden = true
            make.text = "加速匹配中..."
            make.frame = CGRect(x: 0, y: ap_kStatusHeight + 279, width: ap_kScreenW, height: 24)
            make.textAlignment = .center
        }
        return lb
    }()
    
    private var longGestureRecognizer: UILongPressGestureRecognizer!
    private var longPressTimer: Timer?
    private var countDownTotalTime: Int = 0
    
    private lazy var player: SVGAPlayer = {
        let p = SVGAPlayer()
        p.loops = 1
        p.clearsAfterStop = true
        p.contentMode = .scaleAspectFit
        return p
    }()

    private lazy var parser: SVGAParser = {
        let p = SVGAParser()
        return p
    }()

    override func createUI() {
        super.createUI()
        
        radarImageView = UIImageView().then({ make in
            addSubview(make)
            make.image = UIImage(named: "ap_chat_matching_radar")
            make.isUserInteractionEnabled = true
            make.snp.makeConstraints { make in
                make.size.equalTo(188)
                make.centerX.equalToSuperview()
                make.top.equalTo(ap_kStatusHeight + 69)
            }
        })
        
        addSubview(player)
        player.isHidden = true
        player.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        let tempV = UIView().then { make in
            addSubview(make)
            make.backgroundColor = .clear
            make.snp.makeConstraints { make in
                make.size.equalTo(188)
                make.centerX.equalToSuperview()
                make.top.equalTo(ap_kStatusHeight + 69)
            }
        }
        
        heartImageView = UIImageView().then({ make in
            tempV.addSubview(make)
            make.isUserInteractionEnabled = true
            make.image = UIImage(named: "ap_chat_matching_heart")
            make.frame = CGRect(x: 68, y: 72, width: 52, height: 44)
        })
        
        longGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(_:)))
        heartImageView.addGestureRecognizer(longGestureRecognizer)
        
        loopView = GBChatMatchHeadLoopView().then({ make in
            addSubview(make)
            make.snp.makeConstraints { make in
                make.centerX.left.right.equalToSuperview()
                make.top.equalTo(radarImageView.snp.bottom).offset(14)
                make.height.equalTo(19)
            }
        })

        _ = UIButton(type: .custom).then({ make in
            addSubview(make)
            make.titleLabel?.font(.ap.medium(10))
            make.setTitle("什么是聊天匹配？", for: .normal)
            make.setTitleColor(.ap.hex("FFCC47"), for: .normal)
            make.addTarget(self, action: #selector(whatsChatMatctAction), for: .touchUpInside)
            make.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.height.equalTo(23)
                make.top.equalTo(radarImageView.snp.bottom).offset(65)
            }
        })
        
        startScan()
    }
    
    public func startScan() {
        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotationAnimation.fromValue = 0
        rotationAnimation.toValue = Double.pi * 2
        rotationAnimation.duration = 2
        rotationAnimation.repeatCount = HUGE
        rotationAnimation.isRemovedOnCompletion = false
        radarImageView.layer.add(rotationAnimation, forKey: nil)
        debugPrint("雷达- speed is 11 \(radarImageView.layer.speed)")

        startHeartAnimation(isLongPress: false)
    }
    
    public func startHeartAnimation(isLongPress: Bool) {
        heartImageView.layer.removeAnimation(forKey: "chatMatchHeartAnimation")
        let keyframeAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
        keyframeAnimation.fillMode = .backwards
        keyframeAnimation.repeatCount = HUGE
        keyframeAnimation.isRemovedOnCompletion = false
        if isLongPress {
            keyframeAnimation.keyTimes = [0, 0.25, 0.55, 0.8, 1.0]
            keyframeAnimation.values = [1.0, 0.9, 1.08, 0.94, 1.0]
            keyframeAnimation.duration = 1
        } else {
            keyframeAnimation.keyTimes = [0, 0.17, 0.37, 0.54, 0.67, 1]
            keyframeAnimation.values = [1.0, 0.9, 1.08, 0.94, 1.0, 1.0]
            keyframeAnimation.duration = 1.5
        }
        
        keyframeAnimation.timingFunction = CAMediaTimingFunction(name: .easeOut)
        heartImageView.layer.add(keyframeAnimation, forKey: "chatMatchHeartAnimation")
    }
    
    @objc private func whatsChatMatctAction() {
        debugPrint("点击了什么时聊天匹配？")
    }
    
    //!!!: 长摁中间❤️事件
    @objc private func longPressAction(_ gesture: UILongPressGestureRecognizer) {
        if gesture.state == .began {
            beginLongPress()
        } else if gesture.state == .ended || gesture.state == .cancelled || gesture.state == .failed {
            endLongPress()
        }
    }
    
    private func beginLongPress() {
        playSVGA()
        
        loopView.isHidden = true
        speedUpMatchingLabel.isHidden = false

        startHeartAnimation(isLongPress: true)
        
        let beginTimeOffset = radarImageView.layer.convertTime(CACurrentMediaTime(), from: nil)
        radarImageView.layer.timeOffset = beginTimeOffset
        debugPrint("雷达- beginTimeOffset is \(beginTimeOffset)")

        let beginBeginTime = CACurrentMediaTime()
        radarImageView.layer.beginTime = beginBeginTime
        debugPrint("雷达- beginBeginTime is \(beginBeginTime)")

        debugPrint("雷达- speed is 22 \(radarImageView.layer.speed)")
        radarImageView.layer.speed += 0.75
        debugPrint("雷达- speed is 33 \(radarImageView.layer.speed)")
    }
    
    private func endLongPress() {
        stopSVGA()

        loopView.isHidden = false
        speedUpMatchingLabel.isHidden = true
        
        startHeartAnimation(isLongPress: false)
        
        let endTimeOffset = radarImageView.layer.convertTime(CACurrentMediaTime(), from: nil)
        radarImageView.layer.timeOffset = endTimeOffset
        debugPrint("雷达- endTimeOffset is \(endTimeOffset)")

        let endBeginTime = CACurrentMediaTime()
        radarImageView.layer.beginTime = endBeginTime
        debugPrint("雷达- endBeginTime is \(endBeginTime)")
        
        debugPrint("雷达- speed is 44 \(radarImageView.layer.speed)")
        radarImageView.layer.speed -= 0.75
        debugPrint("雷达- speed is 55 \(radarImageView.layer.speed)")
    }
    
    private func playSVGA() {
        guard let path = Bundle.main.path(forResource: "ap_chat_match_emitter", ofType: "svga") else { return }
        guard FileManager.default.fileExists(atPath: path) else { return }

        guard let data = NSData(contentsOfFile: path) as? Data else { return }
        player.isHidden = false
        parser.parse(with: data, cacheKey: path) { [weak self] (videoItem) in
            self?.player.videoItem = videoItem
            self?.player.startAnimation()
        }
    }
    
    private func stopSVGA() {
        player.isHidden = true
        player.stopAnimation()
    }
}
